<template>
    <div style="width: 100%; height: 100%;">
        <div class="record_search" style="background-color: #EDF0FE;">
            <div class="record_search_time">
                <div class="name">历史盘煤日期:</div>
                <div class="item date-container">
                    <el-date-picker v-model="queryDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                                    placeholder="请选择" :disabled-date="disabledDate" :editable="false" :clearable="true" @change="handleDateChange" @visible-change="handlePanelToggle" />
                    <!-- 数据展示区域 -->
                    <transition name="el-zoom-in-top">
                        <div v-if="showContent" class="floating-data">
                            <div class="popper-arrow"></div>
                            <template v-if="currentData.length">
                                <div v-for="item in currentData"
                                     class="file-item"
                                     @click="handleItemClick(item)">
                                    {{ item["recordName"] }}
                                </div>
                            </template>
                            <div v-else class="empty-tip">
                                所选日期内没有盘煤数据。
                            </div>
                        </div>
                    </transition>
                </div>
            </div>
            <div class="record_search_time">
                <table style="border-collapse: separate; border-spacing: 10px; margin-top: 5px; margin-bottom: 5px;">
                    <tr>
                        <td>
                            <div class="name">操作项:</div>
                        </td>
                        <td>
                            <div class="item">
                                <el-button type="primary" color="#2565C8" @click="executeCommand(1)" size="small" round>放大</el-button>
                                <el-button type="primary" color="#2565C8" @click="executeCommand(2)" size="small" round>缩小</el-button>
                                <el-button type="primary" color="#2565C8" @click="executeCommand(3)" size="small" round>移动</el-button>
                                <el-button type="primary" color="#2565C8" @click="executeCommand(4)" size="small" round>旋转</el-button>
                                <el-button type="primary" color="#2565C8" @click="executeCommand(5)" size="small" round>复位</el-button>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <div class="name">显示项:</div>
                        </td>
                        <td>
                            <div class="item">
                                <!--<el-button type="primary" color="#2565C8" @click="executeCommand(6)" size="small" round>显示堆体</el-button>-->
                                <el-button type="primary" color="#2565C8" @click="executeCommand(7)" size="small" round>穹顶</el-button>
                                <el-button type="primary" color="#2565C8" @click="executeCommand(8)" size="small" round>顶部结构</el-button>
                                <el-button type="primary" color="#2565C8" @click="executeCommand(9)" size="small" round>围墙</el-button>
                                <el-button type="primary" color="#2565C8" @click="executeCommand(10)" size="small" round>堆取料机</el-button>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        <div>
            <iframe :src="state.bunkerthreeUrl" ref="penlinMyIframe" frameborder="0" style="width:100%; min-height:800px;"></iframe>
        </div>
    </div>
</template>
<script setup lang="ts">
    import { ref, onMounted, reactive, readonly } from "vue";
    import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
    import { getAllBunkerData } from "./systemDeviceTEnvmonitor";
    import { getFuelWorkTInventoryById, getTheLatestyorkRecord, getHistory } from "./fuelWorkTInventoryInfo";
    import { getConfigKey } from "./config";
    import dayjs from 'dayjs';

    const penlinMyIframe = ref<HTMLIFrameElement | undefined>(undefined);
    const emit = defineEmits(["bunker", "bunkerinfo"]);

    const commandConfig = reactive({
        baseCommand: "PressMenu$",
        pairs: [
            '无效',
            '放大',
            '缩小',
            '移动',
            '旋转',
            '复位',
            '显示堆体',
            '穹顶状态',
            '顶部结构状态',
            '围墙状态',
            '堆取料机状态'
        ]
    });

    // 创建只读代理对象
    const configs = readonly(commandConfig);

    const queryDate = ref('')
    const lastSelectedDate = ref('');

    const minDate = ref(dayjs('2023-06-30'));
    const maxDate = ref(dayjs());
    const dataCache = ref<Record<string, any>>({});
    const currentData = ref([]);
    const showContent = ref(false);

    const disabledDate = (time: string) => {
        return dayjs(time).isBefore(minDate.value) || dayjs(time).isAfter(maxDate.value);
    };

    const handlePanelToggle = (isVisible: boolean) => {
        if (isVisible) {
            showContent.value = false;
        }
        else {
            if (lastSelectedDate && dayjs(lastSelectedDate.value).isSame(dayjs(queryDate.value), "day")) {
                showContent.value = true;
            }
        }
    };

    const handleDateChange = async (date: string) => {
        if (!date) return;

        lastSelectedDate.value = date;

        var k = `${state.value.bunkerNo}-${date}`;
        var currentValue = dataCache.value[k];
        if (currentValue) {
            currentData.value = currentValue;
            showContent.value = true;
            return;
        }

        showContent.value = false

        try {
            getHistory(state.value.bunkerId, date).then(response => {
                currentData.value = response.data.dataFound ? response.data.histories : [];

                dataCache.value[k] = currentData.value;

                showContent.value = true;
            });
        } catch (e) {
            dataCache.value[k] = [];
            currentData.value = [];
        }
    }

    const handleItemClick = (item: any) => {
        const iframe = penlinMyIframe.value;
        var fileNameJson =
            state.value.fileBaseUrl +
            state.value.bunkerNo +
            "Stockyard" +
            "/" +
            item.recordName +
            "/" +
            item.recordName +
            ".json";

        const paraData = [
            {
                yardNumber: item.bunkerId,
                fileList: [fileNameJson]
            }
        ];
        setTimeout(() => {
            const jfile = JSON.stringify(paraData);
            console.log(jfile);
            iframe?.contentWindow?.postMessage(
                "FileAddress$" + jfile,
                state.value.bunkerthreeUrl
            );
        }, 1000);

        showContent.value = false;

        ElMessage.success({
            message: '正在加载选定的盘煤历史数据，请稍后......',
            type: 'success',
            duration: 3000
        });
    }

    export interface InBunker {
        bunkerId: number | undefined;
        parentGroupId: string | undefined;
        bunkerType: string | undefined;
        parentFqIndexId: string | undefined;
        bunkerName: string | undefined;
        stackNo: number | undefined;
        posNo: string | undefined;
        maxCoalWeight: number | undefined;
        curPrice: number | undefined;
        curHeat: number | undefined;
        curBulk: number | undefined;
        curWeight: number | undefined;
        lastInventoryTime: string | undefined;
        stackLength: number | undefined;
        stackWidth: number | undefined;
        stackInRad: number | undefined;
        stackOutRad: number | undefined;
        stackCircHigh: number | undefined;
        deviceBaseHigh: number | undefined;
        deviceLength: number | undefined;
        maxElevation: number | undefined;
        minElevation: number | undefined;
        remark: string | undefined;
        refStockyardId: string | undefined;
        ip: string | undefined;
        port: number | undefined;
    }
    const props = defineProps<{
        bunkerId?: number;
        /** 不需要获取煤堆信息 */
        bunkerGetNo?: boolean;
        executeId?: number;
    }>()
    interface InState {
        bunkerData: InBunker[];
        bunkerId: number;
        bunkerthreeUrl: string;
        bunkerValueData: any[];
        fileBaseUrl: string;
        bunkerNo: number;
        userCount: number;
    }
    let state = ref<InState>({
        bunkerData: [],
        bunkerId: 0,
        bunkerthreeUrl: "",
        bunkerValueData: [],
        fileBaseUrl: "",
        bunkerNo: 0,
        userCount: 0
    });
    onMounted(() => {
        getConfigKey("threeImgUrl").then(response => {
            state.value.bunkerthreeUrl = response.data;
        });
        getConfigKey("bunkerFileUrl").then(response => {
            state.value.fileBaseUrl = response.data;
        });
        if (!props.bunkerGetNo) {
            getAllBunkerData().then(response => {
                state.value.bunkerData = response.data;
                let currentBunkerId = response.data[0].bunkerId;
                state.value.bunkerId = currentBunkerId;
                state.value.bunkerNo = response.data[0].stackNo;
                emit("bunker", state.value.bunkerData);
            });
        }
        if (props.bunkerId) {
            setTimeout(() => {
                handleSelectChange(props.bunkerId, props.executeId);
            }, 1000);
        }
    });

    function handleSelectChange(bunkerId?: number, executeId?: number) {
        executeCommand(4);
        if (bunkerId) {
            state.value.bunkerId = bunkerId;
        }
        const currentData = state.value.bunkerData.find(
            tab => tab.bunkerId === state.value.bunkerId
        );
        state.value.bunkerNo = currentData?.stackNo ?? 0;
        bunkerIframeload();
        getLatestyorkRecord(state.value.bunkerId, executeId);
    }
    function bunkerIframeload() {
        queryDate.value = '';
        showContent.value = false;
        currentData.value = [];
        lastSelectedDate.value = '';

        getFuelWorkTInventoryById(state.value.bunkerId).then((res: any) => {
            if (res.code == 200) {
                emit("bunkerinfo", res.data);
            }
        });
    }
    function getLatestyorkRecord(bunkerId: number, executeId?: number) {
        const iframe = penlinMyIframe.value;
        if (iframe?.contentWindow) {
            getTheLatestyorkRecord(bunkerId, executeId).then((res: any) => {
                if (res.code == 200) {
                    if (res.data.specifiedDataNotFound) {
                        ElMessage.warning({
                            message: '由于指定的盘煤记录数据未找到，正在加载最新的盘煤记录，请稍后......',
                            type: 'warning',
                            duration: 5000
                        });
                    }
                    const currentData = res.data;
                    var fileNameJson =
                        state.value.fileBaseUrl +
                        state.value.bunkerNo +
                        "Stockyard" +
                        "/" +
                        currentData.fileName +
                        "/" +
                        currentData.fileName +
                        ".json";
                    console.log(fileNameJson);
                    const paraData = [
                        {
                            yardNumber: currentData.parent_bunker_id,
                            fileList: [fileNameJson]
                        }
                    ];
                    setTimeout(() => {
                        const jfile = JSON.stringify(paraData);
                        console.log(jfile);
                        iframe?.contentWindow?.postMessage(
                            "FileAddress$" + jfile,
                            state.value.bunkerthreeUrl
                        );
                    }, 1000);

                    if (!res.data.specifiedDataNotFound) {
                        ElMessage.success({
                            message: '正在加载盘煤历史数据，请稍后......',
                            type: 'success',
                            duration: 3000
                        });
                    }
                }
            })
        } else {
            setTimeout(() => {
                getLatestyorkRecord(state.value.bunkerId);
            }, 1000);
        }
    }

    function executeCommand(type: number) {
        if (type > 0) {
            const commandMessage = `${commandConfig.baseCommand}${configs.pairs[type]}`;

            penlinMyIframe.value?.contentWindow?.postMessage(
                commandMessage,
                state.value.bunkerthreeUrl
            );
        }
        else {
            ElMessage.error("无效命令....");
        }
    }
    defineExpose({
        handleSelectChange
    });
</script>
<style scoped lang="scss">
    .date-container {
        position: relative;

        .floating-data {
            top: 50px;
            margin-top: 6px;
            position: absolute;
            width: 100%;
            top: 45px;
            left: 0;
            background: white;
            border: 1px solid #e4e7ed;
            border-radius: 4px;
            box-shadow: 0 2px 12px rgba(0,0,0,.1);
            z-index: 2000;
            padding: 12px;
            transition: opacity 0.2s, transform 0.2s;
        }

        .file-item {
            cursor: pointer;
            padding: 8px 15px;
            border-radius: 3px;
            transition: all 0.3s;
        }

        .file-item:hover {
            background: #409eff;
            color: white;
            transform: translateY(-2px);
        }

        .empty-tip {
            color: #909399;
            font-size: 14px;
        }

        .popper-arrow {
            position: absolute;
            top: -6px;
            left: 50%;
            transform: translateX(-50%);
            width: 12px;
            height: 6px;
            z-index: -1;

            &::before {
                content: '';
                position: absolute;
                border-color: transparent;
                border-style: solid;
                border-width: 0 6px 6px;
                border-bottom-color: #fff;
                filter: drop-shadow(0 -2px 1px rgba(0,0,0,0.06));
            }

            &::after {
                content: '';
                position: absolute;
                border-color: transparent;
                border-style: solid;
                border-width: 0 6px 6px;
                top: -5px;
            }
        }
    }
</style>